package com.ponhu.ea2.goodsCenter.provider.utils;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ponhu.ea2.common.basic.model.ResponseBean;
import com.ponhu.ea2.dto.InventoryMaintainResultDto;
import com.ponhu.ea2.vo.DingTalkContentVO;
import com.ponhu.ea2.wmscenter.model.utils.HttpClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author luyu
 * @create 2021-11-06 17:54
 */
@Slf4j
@Component
@RefreshScope
public class DingTalkHandler {

    @Value("${ponhu.dingTalk.url}")
    private String url;

    @Value("${spring.profiles.active}")
    private String active;

    private final String ponhuName = "【胖总管】";

    private final String juWoName = "【巨沃】";

    private final String stockName = "【库存】";

    private final String chuangjiCloudName = "【创纪云】";

    /**
     * 发送钉钉机器人消息
     *
     * @param content    发送内容
     * @param mobileList 通知具体人的手机号码列表
     */
    public void sendMsg(String content, List<String> mobileList) {
        sendMsg(content, mobileList, false);
    }

    /**
     * 发送markDown格式数据
     * @param dingTalkContentVO
     */
    public void sendMsg(DingTalkContentVO dingTalkContentVO) {
        if (dingTalkContentVO != null) {
            sendMsg(dingTalkContentVO.toString(), new ArrayList<>(), true);
        }
    }

    private void sendMsg(String content, List<String> mobileList, boolean isMarkDown) {
        try {
            //是否通知所有人
            boolean isAtAll = false;

            //如果具体人的手机号码列表为空则通知所有人
            if (CollectionUtils.isEmpty(mobileList)) {
                isAtAll = true;
                mobileList = Lists.newArrayList();
            }

            //组装请求内容
            String reqStr = buildReqStr(content, isAtAll, mobileList, isMarkDown);

            //推送消息（http请求）
            String result = HttpClient.getInstance().doPostJson(url, reqStr);
            log.info("发送钉钉机器人消息成功 ===>> Content={}", result);
        } catch (Exception e) {
            log.error("发送钉钉机器人消息异常 ===>> Error={}", e.getMessage());
        }
    }


    /**
     * 组装请求报文
     *
     * @param content
     * @param isAtAll    是否通知所有人
     * @param mobileList 通知指定的手机号，具体到某个人
     * @return
     */
    private static String buildReqStr(String content, boolean isAtAll,
                                      List<String> mobileList,  boolean isMarkDown) {
        if(isMarkDown){
            //消息内容
            Map<String, String> contentMap = Maps.newHashMap();
            contentMap.put("title", "推送失败:商品中心");
            contentMap.put("text", content);
            //通知人
            Map<String, Object> atMap = Maps.newHashMap();
            //是否通知所有人
            atMap.put("isAtAll", isAtAll);
            //通知具体人的手机号码列表
            atMap.put("atMobiles", mobileList);
            Map<String, Object> reqMap = Maps.newHashMap();
            reqMap.put("msgtype", "markdown");
            reqMap.put("markdown", contentMap);
            reqMap.put("at", atMap);
            return JSON.toJSONString(reqMap);
        }else {
            //消息内容
            Map<String, String> contentMap = Maps.newHashMap();
            contentMap.put("content", content);

            //通知人
            Map<String, Object> atMap = Maps.newHashMap();
            //是否通知所有人
            atMap.put("isAtAll", isAtAll);
            //通知具体人的手机号码列表
            atMap.put("atMobiles", mobileList);
            Map<String, Object> reqMap = Maps.newHashMap();
            reqMap.put("msgtype", "text");
            reqMap.put("text", contentMap);
            reqMap.put("at", atMap);
            return JSON.toJSONString(reqMap);
        }

    }

    /**
     *  推送胖总管的钉钉消息
     * @param map
     * @return
     */
    public String getMsgForPonHuByCreate(Map map, MultiValueMap<String, Object> multiValueMap,String createdUrl){
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(active.toUpperCase())
                .append("-推送"+ponhuName+"失败:商品中心")
                .append("[goodsCenterForPonHuService:createGoodsInfoForPonHu]")
                .append("调用"+ponhuName+"发布商品接口地址为:"+createdUrl)
                .append(",发布商品信息失败,推送数据为:")
                .append(multiValueMap)
                .append(","+ponhuName+"返回消息为:")
                .append(map)
                .append(",请检查原因");
        return stringBuffer.toString();
    }

    public String getMsgForPonHuByUpdate(Map map, MultiValueMap<String, Object> multiValueMap,String updateUrl){
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(active.toUpperCase())
                .append("-推送"+ponhuName+"失败:商品中心")
                .append("[goodsCenterForPonHuService:updateGoodsInfoForPonhu]")
                .append("调用"+ponhuName+"编辑接口地址:"+updateUrl)
                .append(",更新商品信息失败,推送的数据为:")
                .append(multiValueMap)
                .append(","+ponhuName+"返回消息为:")
                .append(map)
                .append(",请检查原因");
        return stringBuffer.toString();
    }


    public String getDingDingMsgForWms(String inventoryCode, ResponseBean responseBean) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(active.toUpperCase())
                .append("-推送"+juWoName+"失败:商品中心")
                .append("[GoodsCenterForWMSServiceImpl:createOrUpdateGoodsForWms]")
                .append("推送"+juWoName+"发生异常,货品编码为:")
                .append(inventoryCode)
                .append(",wms信息为:")
                .append(responseBean)
                .append(",请检查原因");
        return stringBuffer.toString();
    }

    public String getDingDingMsgForStock(String inventoryCode,Long goodsId) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(active.toUpperCase())
                .append("-推送"+stockName+"失败:商品中心")
                .append("[InvokeStockCenterInterfaceServiceImpl:createAndInitRealStockData]")
                .append("推送"+stockName+"发生异常,货品编码为:")
                .append(inventoryCode)
                .append(",商品id为:")
                .append(goodsId)
                .append(",请检查原因");
        return stringBuffer.toString();
    }

    public String getMsgForChuangjiCloud(String reslut, String inventoryCode) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(active.toUpperCase())
                .append("-推送"+chuangjiCloudName+"失败:商品中心")
                .append("[GoodsCenterForChuangjiServiceImpl:phInventoryUpdateToChuangji]")
                .append("货品编码为:")
                .append(inventoryCode)
                .append(",返回结果为:")
                .append(reslut)
                .append(",请检查原因");
        return stringBuffer.toString();
    }

    public String getMsgForApplet(Integer type, String inventory,String msg) {
        StringBuffer stringBuffer = new StringBuffer();
        return stringBuffer.append(active.toUpperCase())
                .append("-推送【会员小程序】失败:商品中心")
                .append("[PhinventoryToAmqpService:pushDataToAmqp]")
                .append("货品编码为：")
                .append(inventory).append(",类型为：").append(type)
                .append(", 错误消息为:").append(msg)
                .append(",请检查原因").toString();
    }

    public String getMsgForMaintainResult(InventoryMaintainResultDto inmaintrsl,String errorMsg) {
        return new StringBuffer().append(active.toUpperCase())
                .append("-商品中心,更新养护结果失败:")
                .append("入参为：").append("\n")
                .append(JSON.toJSONString(inmaintrsl))
                .append(", ").append("\n")
                .append("错误原因为:")
                .append(errorMsg).toString();
    }
}
